// models/form.model.ts
import { GridDefinition } from './grid.model';
import { DataMetaModel } from './meta-model.model';

/**
 * 完整的表单定义
 */
export class FormDefinition {
  name: string = '未命名表单';
  gridDefinition: GridDefinition = new GridDefinition();
  /** 表单关联的数据元模型 */
  dataMetaModel?: DataMetaModel; // 用户选择的元模型

  constructor(initial?: Partial<FormDefinition>) {
    Object.assign(this, initial);
    if (!this.gridDefinition) this.gridDefinition = new GridDefinition();
  }

  /**
   * 将表单定义序列化为JSON字符串
   */
  public toJson(): string {
    // 注意：Map 不能直接 JSON.stringify，需要转换
    const gridDef = {
      ...this.gridDefinition,
      cells: Array.from(this.gridDefinition.cells.entries()),
    };
    return JSON.stringify({ ...this, gridDefinition: gridDef });
  }

  /**
   * 从JSON字符串反序列化为FormDefinition实例
   */
  public static fromJson(jsonString: string): FormDefinition {
    const parsed = JSON.parse(jsonString);

    // 特殊处理 GridDefinition 和 CellDefinition Map 以及 ContentDefinition 的类型恢复
    const formDef = new FormDefinition();
    Object.assign(formDef, parsed);

    // 恢复 GridDefinition
    if (parsed.gridDefinition) {
      formDef.gridDefinition = new GridDefinition(parsed.gridDefinition); // 传递rowCount, colCount等
      formDef.gridDefinition.rows = parsed.gridDefinition.rows.map(
        (r: any) => new RowDefinition(r.index, r.height, r.style)
      );
      formDef.gridDefinition.cols = parsed.gridDefinition.cols.map(
        (c: any) => new ColumnDefinition(c.index, c.width, c.style)
      );

      // 恢复 cells Map 和 ContentDefinition 的具体类型
      const cellsArray: [string, any][] = parsed.gridDefinition.cells;
      formDef.gridDefinition.cells = new Map<string, CellDefinition>();
      cellsArray.forEach(([key, cellData]) => {
        const cell = new CellDefinition(
          cellData.rowIndex,
          cellData.colIndex,
          cellData
        );
        if (cellData.content) {
          // 根据 content.type 恢复具体的内容类实例
          const ContentClass = this.getContentClassByType(
            cellData.content.type
          );
          if (ContentClass) {
            cell.content = new ContentClass(cellData.content);
          } else {
            console.warn(
              `Unknown content type: ${cellData.content.type} for cell ${key}`
            );
            // 可以设置一个默认的 ContentDefinition 或 null
          }
        }
        formDef.gridDefinition.cells.set(key, cell);
      });
    }

    // 恢复 DataMetaModel
    if (parsed.dataMetaModel) {
      formDef.dataMetaModel = new DataMetaModel(
        parsed.dataMetaModel.name,
        parsed.dataMetaModel.isCollection,
        parsed.dataMetaModel.fields
      );
    }

    return formDef;
  }

  private static getContentClassByType(type: string): any | null {
    // 需要在这里维护一个映射
    // models/content.model.ts 中引入所有内容类
    const {
      TextContent,
      InputContent,
      ImageContent,
    } = require('./content.model'); // 动态导入或提前导入

    switch (type) {
      case 'text':
        return TextContent;
      case 'input':
        return InputContent;
      case 'image':
        return ImageContent;
      // case 'employee-selector': return EmployeeSelectorContent;
      default:
        return null;
    }
  }
}
